﻿using BCVP.Net8.IService;
using BCVP.Net8.Model.Models;
using BCVP.Net8.Model.ViwModels;
using BCVP.Net8.Repository.UnitOfWorks;
using BCVP.Net8.Service;

using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;

namespace BCVP.Net8.Controllers
{
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class TransactionController : ControllerBase
    {
        private readonly IBaseService<Role, RoleViewModel> _roleService;
        private readonly IUnitOfWorkManage _unitOfWorkManage;
        private readonly IUserService _userService;

        public TransactionController(IBaseService<Role, RoleViewModel> roleService, IUnitOfWorkManage unitOfWorkManage, IUserService userService)
        {
            _roleService = roleService;
            _unitOfWorkManage = unitOfWorkManage;
            _userService = userService;
        }

        [HttpGet]
        public async Task<object> Get()
        {
            try
            {
                Console.WriteLine($"Begin Transaction");

                //_unitOfWorkManage.BeginTran();//简单写法
                using var unit = _unitOfWorkManage.CreateUnitOfWork();

                var roles = await _roleService.QueryAll();
                Console.WriteLine($"1 first time : the count of role is :{roles.Count}");


                Console.WriteLine($"insert a data into the table role now.");
                TimeSpan timeSpan = DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                var insertPassword = await _roleService.Add(new RoleViewModel()
                {
                    IsDeleted = false,
                    RoleName = "role name",
                });

                var roles2 = await _roleService.QueryAll();
                Console.WriteLine($"2 second time : the count of role is :{roles2.Count}");


                int ex = 0;
                Console.WriteLine($"There's an exception!!");
                Console.WriteLine($" ");
                int throwEx = 1 / ex;


                //_unitOfWorkManage.CommitTran();//简单写法

                unit.Commit();

                Console.WriteLine("Commit Transaction");
            }
            catch (Exception)
            {
                //_unitOfWorkManage.RollbackTran();//简单写法
                Console.WriteLine("RollBack Transaction");
                var roles3 = await _roleService.QueryAll();
                Console.WriteLine($"3 third time : the count of role is :{roles3.Count}");
            }

            return "ok";
        }

        [HttpGet]
        public async Task<object> TestTranPropagation()
        {
            return await _userService.TestTranPropagation();
        }
    }
}
